﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotaHelp.Models;
using System.Web.UI;
using System.Text.RegularExpressions;
using System.Web.Caching;
using System.Drawing;
using System.IO;
using System.Xml.Linq;
using DotaHelp.Helpers;
using System.Text;
using Sandbox.AddressBook.Web.Client.Application.Mvc;
using System.ServiceModel.Syndication;
using System.Data.Objects;

namespace DotaHelp.Controllers
{
    
    public class HomeController : Controller
    {
        DotaModel model = new DotaModel();

        protected override void Dispose(bool disposing)
        {            
            base.Dispose(disposing);
            model.Dispose();
            
        }      

		[Sitemap]		
		public ActionResult Menu()
		{
			return View();			
		}
		
		public ActionResult MenuPartial()
		{
			ViewBag.AddCss = false;
			return PartialView("Menu");
		}

        public ActionResult About()
        {
            return View();
        }

        [Sitemap]
        public ActionResult GuestBook()
        {
            return View();
        }
      
        public ActionResult Error(string error)
        {
            return View((object)error);
        }


        [IfModified("Image", "id")]      
        public ActionResult Image(int id)
        {
            if (Request.UrlReferrer != null && Request.UrlReferrer.AbsoluteUri.Contains("morph-game.ru"))
            {
                return Redirect("http://mrazish.com/wp-content/uploads/2011/10/azis_p301-600x300.jpg");
            }

            var img = model.Images.First(_ => _.Id == id);
            /*if (img.HosterUrl != null)
            {
                return Redirect(img.HosterUrl);
            }*/

            return new FileContentResult(img.Data, img.ContentType); 
        }
        
        [IfModified("StrikeImage", "id")]       
        public ActionResult StrikeImage(int id) 
        { 
            var img = model.Images.First(_ => _.Id == id); 
            using (var stream = new MemoryStream(img.Data))
            using (var bitmap = new Bitmap(stream)) 
            using (var bitmap2 = new Bitmap(bitmap.Width, bitmap.Height)) 
            {
                using (var gr = Graphics.FromImage(bitmap2))
                {
                    gr.DrawImage(bitmap, 0, 0);

                    gr.DrawLine(new Pen(Color.Red, 5), 0, 0, bitmap.Width, bitmap.Height);
                    gr.DrawLine(new Pen(Color.Red, 5), bitmap.Width, 0, 0, bitmap.Height);
                }

                using (var ms = new MemoryStream()) 
                { 
                    bitmap2.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); 
                    ms.Position = 0; 
                    return new FileContentResult(ms.ToArray(), "image/jpeg"); 
                }                 
            } 
        }
              
             

        [ChildActionOnly]
        public ActionResult Rating(int id, int current, string controller, string action)
        {
            ViewBag.CanRate = User.IsInRole("Admin") || Session[controller + action + id] == null;                    

            ViewBag.Current = current;
            ViewBag.OnController = controller;
            ViewBag.Id = id;
			ViewBag.OnAction = action;

            return PartialView(current);
        }

        [HttpPost] 
        public ActionResult RatingOn(int id, string onController, string onAction, bool isPlus)
        {
			if (!User.IsInRole("Admin") && Session[onController + onAction + id] != null)
            {
				throw new MessageException("Вы уже голосовали за него");
            }

			Session.Add(onController + onAction + id, true);           
            
            ViewBag.OnController = onController;
			ViewBag.OnAction = onAction;
            ViewBag.Id = id;
            ViewBag.IsPlus = isPlus;

            return PartialView();
        }

      
		       
        public ActionResult Tenders()
        {
            return View();
        }


        private class Utf8StringWriter : StringWriter
        {
            public override Encoding Encoding { get { return Encoding.UTF8; } }
        }

        [Sitemap]
        public ActionResult Sitemap()
        {
            Func<string, XName> n = name=>XName.Get(name, "http://www.sitemaps.org/schemas/sitemap/0.9");
            Func<string, DateTime?, XElement> v = (url, date) => new XElement(n("url")
                , new XElement(n("loc"), url)
                , date.HasValue ? new XElement(n("lastmod"), date.Value.ToString("yyyy-MM-dd")) : null
                );

            var result = new XDocument(new XDeclaration("1.0", "utf-8", "no"),
                    new XElement(n("urlset"),
                    DotaHelp.Helpers.SitemapAttribute.Load(Url, v)));

            StringWriter writer = new Utf8StringWriter();
            result.Save(writer, System.Xml.Linq.SaveOptions.None);

            return new ContentResult()
            {
                Content = writer.GetStringBuilder().ToString(),
                ContentEncoding = Encoding.GetEncoding("utf-8"),
                ContentType = "text/xml"
            };
        }

        [Sitemap]
        public ActionResult Robots()
        {
            return new ContentResult()
            {
                Content = DotaHelp.Helpers.SitemapAttribute.Robots(Url),
                ContentType = "text/plain"
            };
        }

        [Authorize]
		[OutputCache(NoStore = true, Location = OutputCacheLocation.None, VaryByCustom = "User")]
        public ActionResult EditField(string tableName, string fieldName, int id)
        {
			if (User.IsInRole("Admin")
				   || Helper.TablesWhichVipCanEdit.Contains(tableName + "|" + fieldName)
				   || Helper.TablesWhichVipCanEditOnlyHis.Contains(tableName + "|" + fieldName)
			   )
			{

				ViewBag.TableName = tableName;
				ViewBag.FieldName = fieldName;
				var q =model.CreateQuery<object>(string.Format("SELECT VALUE t.{0} FROM  DotaModel.{1} AS t WHERE t.Id = @id", fieldName, tableName)
					, new ObjectParameter("id", id));
				
				ViewBag.CurrentValue = q.First().ToString();
				ViewBag.Id = id;
				return PartialView();
			}

			throw new MessageException("Нет прав");
        }

        [Authorize]
        [ValidateInput(false)]
        public ActionResult SaveField(string tableName, string fieldName, int id, string value)
        {
            if (User.IsInRole("Admin") 
					|| Helper.TablesWhichVipCanEdit.Contains(tableName + "|" + fieldName)
					|| Helper.TablesWhichVipCanEditOnlyHis.Contains(tableName + "|" + fieldName)
				)
            {
                try
                {
                    model.UpdateField(tableName, fieldName, id, value, User.Identity.Name);
                }
                catch (Exception)
                {
                     
                }
            }
            return Redirect(Request.UrlReferrer.AbsoluteUri);
        }

        public ActionResult ListOfChanges(int? page)
        {
            return View(model.UpdateFieldLogs.ByPage(page, "", null, c => c.Date, ViewData, HttpContext));
        }

		public ActionResult Search(string q)
		{
			return View();
		}

        [Sitemap]
        [OutputCache(Duration=60, Location=OutputCacheLocation.Server)]
        public ActionResult Rss()
        {           
            return new RssActionResult(RssAttribute.Load(this));
        }

		
    }
}
